import {config} from "./config.js";

class HTTP {

    request({
        url,
        data = {},
        method = 'POST',
        header = {},
        loadingStatus = true
    }) {
        return new Promise((resolve, reject) => {
            this._request(url, resolve, reject, data, method, header, loadingStatus);
        }).catch(function(reason) {
            console.log("catch: ", reason);
        })
    }

    _request(url, resolve, reject, data, method, header, loadingStatus) {
        if (loadingStatus) {
            wx.showLoading({
                title: "加载中..."
            })
        }
        let token = wx.getStorageSync('token');
        if (token) {
            header.token = token;
        } else {
            header.token = "";
        }

        wx.request({
          url: config.api_base_url + url,
          data: data,
          method: method,
          header: Object.assign(config.header, header),
          success: res => {
              if (res.data.error_code && res.data.error_code == '0') {
                  // 请求成功
                  wx.setStorage({
                      key: 'token',
                      data: res.data.token
                  })
              } else if (res.data.error_code && res.data.error_code == '-1') {
                  wx.showToast({
                    title: '登录过期，正在跳转登录页面！',
                    icon: 'none',
                    duration: 2000
                  })
                  setTimeout(() => {
                      wx.hideToast();
                      wx.redirectTo({
                        url: '/pages/login/login',
                      })
                  }, 1500)
              }
              if (loadingStatus) {
                  wx.hideLoading();
              }

              resolve(res.data);
          },
          fail: err => {
              reject();
              this._show_error(err);
              if (res.data.code != 'MA1101') {
                  if (loadingStatus) {
                      wx.hideLoading();
                  }
              }
          }
        })
    }

    _show_error(error_msg) {
        let tip = "";
        error_msg ? tip = error_msg : tip = '抱歉，出现了一个错误';
        wx.showToast({
          title: tip,
          icon: 'none',
          duration: 2000
        })
    }
}

export {
    HTTP
}